<template>
  <BasicModal
    @ok="okFun"
    :title="t('table.member.member_import_members')"
    :okText="t('table.member.member_confirm_upload')"
    :cancelText="t('business.common_cancel')"
    @register="registeraddDemond"
    :showCancelBtn="false"
    :width="800"
    :maskClosable="false"
  >
    <BasicForm @register="registeraddDemondForm">
      <template #importSlot="{ model, field }">
        <FormItemRest>
          <ImpExcel @success="loadDataSuccess" dateFormat="YYYY-MM-DD" class="w-128px">
            <a-button v-if="showText" :size="FORM_SIZE">
              <cloud-upload-outlined />
              {{ t('table.member.member_import_table') }}Excel
            </a-button>
            <div v-else
              >{{ btnText }}
              <DeleteOutlined @click.stop="deleteExcel" :style="{ color: '#e91134' }"
            /></div>
          </ImpExcel>
        </FormItemRest>
      </template>
    </BasicForm>
    <div class="alert !p-l-141px">
      <div>{{ t('table.member.member_instructions_for_use') }}</div>
      <div class="ml-2">
        <p>. {{ t('table.member.member_update_num') }}</p>
        <p>. {{ t('table.member.member_update_size') }}</p>
        <p class="p1" @click="handleDownloadByUrl"
          >. {{ t('table.member.member_download_template') }}
        </p>
      </div>
    </div>
  </BasicModal>
</template>
<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { schemas, transformData, setParamas } from './ImportMembers.data';
  import { message, FormItemRest } from 'ant-design-vue';
  import { useFormSetting } from '/@/hooks/setting/useFormSetting';
  import { ImpExcel, ExcelData } from '/@/components/Excel';
  import { fileUrlHandled } from '/@/utils/file/download';
  import { CloudUploadOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import ZstdCodec from 'zstd-codec';
  import { getToken } from '/@/utils/auth';
  import axios from 'axios';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useI18n } from '@/hooks/web/useI18n';

  const { t } = useI18n();
  const globSetting = useGlobSetting();
  const emit = defineEmits(['diamondsuccess', 'importSuccess', 'register', 'enable']);
  const FORM_SIZE = useFormSetting().getFormSize;
  const btnText = ref<any>('');
  const showText = ref<any>(true);
  const getExcelData = ref([] as any);
  const [registeraddDemondForm, { setFieldsValue, validate, resetFields }] = useForm({
    labelAlign: 'right',
    showResetButton: false,
    showSubmitButton: false,
    schemas,
    size: FORM_SIZE,
  });

  const [registeraddDemond, { setModalProps, closeModal }] = useModalInner(async (values) => {
    setModalProps({ confirmLoading: false });
    resetFields();
    showText.value = true;
  });

  function deleteExcel() {
    showText.value = true;
    btnText.value = '';
    getExcelData.value = [];
    setFieldsValue({ member: '' });
  }

  async function okFun() {
    try {
      setModalProps({ confirmLoading: true });
      const value = await validate();
      // value.d = resultList.value;
      for (const excelData of getExcelData.value) {
        console.log(excelData);
        const {
          header,
          results,
          meta: { sheetName },
        } = excelData;
        const outputData = transformData(results).filter((item) => {
          return item.username.trim() !== '';
        });
        const arr: any = setParamas(outputData);
        //console.log(outputData)
        for (const item of arr) {
          console.log(arr[item]);
          if (!item?.phone.trim()) {
            message.error(t('table.member.member_import_err1'));
            return;
          } else if (!item?.email.trim()) {
            message.error(t('table.member.member_import_err2'));
            return;
          } else if (!item?.vip.trim()) {
            message.error(t('table.member.member_import_err3'));
            return;
          } else if (!item?.level.trim()) {
            message.error(t('table.member.member_import_err4'));
            return;
          } else if (!item?.realname.trim()) {
            message.error(t('table.member.member_import_err5'));
            return;
          } else if (!item.flag.trim()) {
            message.error(t('table.member.member_import_err6'));
            return;
          }
          //return false
        }
        value['member'] = arr;

        function encodeSearchParams(obj) {
          const params = [];

          Object.keys(obj).forEach((key) => {
            let value = obj[key];
            // 如果值为undefined我们将其置空
            if (typeof value === 'undefined') {
              value = '';
            }
            // 对于需要编码的文本（比如说中文）我们要进行编码
            params.push([key, encodeURIComponent(value)].join('='));
          });

          return params.join('&');
        }

        const _content = encodeSearchParams(value);

        ZstdCodec.ZstdCodec.run((__zstd) => {
          const token: any = getToken();
          const simple = new __zstd.Simple();
          const _data = new TextEncoder().encode(_content);
          const level = 5;
          const compressed = simple.compress(_data, level);
          axios
            .post(globSetting.apiUrl + '/member/import', compressed, {
              headers: {
                t: token,
                lang: 'zh_CN',
                // 'Content-Type': 'arraybuffer'
                'Content-Type': 'application/octet-stream',
              },
            })
            .then((res) => {
              const { status, data } = res.data;
              if (status) {
                message.success(data);
                closeModal();

                emit('enable');
              } else {
                message.error(data);
              }
            });
        });
      }
    } catch (e) {
      console.log(e);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleDownloadByUrl() {
    fileUrlHandled({
      url: '/assets/xlsx/users_import1.xlsx',
      filename: '会员列表-导入模板.xlsx',
      target: '_self',
    });
  }

  function loadDataSuccess(excelDataList: ExcelData[], name: any) {
    btnText.value = name;
    showText.value = false;
    getExcelData.value = excelDataList;
    for (const excelData of excelDataList) {
      const {
        header,
        results,
        meta: { sheetName },
      } = excelData;
      //console.log(header)
      const columns: any = [];
      const requiredElements = [
        '会员账号',
        '会员姓名',
        '账号类型',
        '会员层级',
        'VIP等级',
        '手机号码',
        '电子邮箱',
      ];
      const containsAllRequiredElements = requiredElements.every((element) =>
        header.includes(element),
      );
      if (!containsAllRequiredElements) {
        return message.error(t('table.member.member_update_err'));
      }
      emit('importSuccess', excelDataList);
      const outputData = transformData(results).filter((item) => {
        return item.username.trim() !== '';
      });
      const arr = setParamas(outputData);
      setFieldsValue({ member: arr });
    }
  }
</script>
<style lang="less" scoped>
  .alert {
    display: flex;
    width: 100%;
    padding: 30px 30px 50px;
    border: 1px solid #78b7e3;
    background-color: #e1effe;
  }

  .p1 {
    color: @primary-color;
    cursor: pointer;
  }
</style>

<style lang="less">
  .import-tooltip {
    .ant-tooltip-inner {
      width: 500px;
    }
  }
</style>
